<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('游戏标签树选择')"/>
    <th:block th:include="include :: ztree-css"/>
</head>
<style>
    body {
        height: auto;
        font-family: "Microsoft YaHei";
    }

    button {
        font-family: "SimSun", "Helvetica Neue", Helvetica, Arial;
    }
</style>
<body class="hold-transition box box-main">

<h3>选择游戏标签</h3>

<!-- zTree 容器 -->
<ul id="tagTree" class="ztree"></ul>

<input id="gameId" type="hidden" th:value="${gameId == null?'0':gameId}"/>

<!-- 显示结果 -->
<div class="selected-list">
    <h4>当前已选择：</h4>
    <p id="result"></p>
</div>

<p id="selectNodeJson" name="selectNodeJson" style="display: none"></p>
</div>
<th:block th:include="include :: footer"/>
<th:block th:include="include :: ztree-js"/>
<script th:inline="javascript">
    var gameId = $('#gameId').val();
    // 存储原始所有节点（用于重置）
    // zTree 配置
    var setting = {
        view: {
            dblClickExpand: false
        },
        data: {
            simpleData: {
                enable: true,
                idKey: "id",
                pIdKey: "pId",
                rootPId: 0
            },
            key: {
                name: "name"
            }
        },
        check: {
            enable: true,      // 启用勾选
            chkboxType: {"Y": "ps", "N": "ps"} // 勾选时影响父和子
        },
        callback: {
            onCheck: zTreeOnCheck
        }
    };

    // 存储当前选中的节点
    var selectedNodes = [];

    // 初始化 zTree
    $(document).ready(function () {
        $.ajax({
            url: '/biz/tag/treeData/' + gameId,
            type: 'GET',
            dataType: 'json',
            success: function (data) {
                $.fn.zTree.init($("#tagTree"), setting, data);
                var zTree = $.fn.zTree.getZTreeObj("tagTree");
                selectedNodes = zTree.getCheckedNodes(true);
                updateResult();

                /* 获取所有树节点 */
                var nodes = zTree.transformToArray(zTree.getNodes());
                //展开第一级树
                zTree.expandNode(nodes[0], true);
            },
            error: function () {
                console.log("加载树数据失败！");
            }
        });
    });

    // 勾选事件回调
    function zTreeOnCheck(event, treeId, treeNode) {
        var zTree = $.fn.zTree.getZTreeObj("tagTree");
        selectedNodes = zTree.getCheckedNodes(true); // 只获取被勾选的
        updateResult();
    }

    // 实时更新显示（可选）
    function updateResult() {
        var result = selectedNodes.map(node => ({
            id: node.id,
            name: node.name,
            pid: node.pid
        }));

        var names = selectedNodes.map(node => node.name) || [];
        //JSON.stringify(result, null, 2);
        document.getElementById('result').textContent = names.join(",");
        document.getElementById('selectNodeJson').textContent = JSON.stringify(result, null, 2);
    }
</script>
</body>
</html>